# 一、将脚本路径添加到python的sys系统环境变量里
import sys

sys.path.append('D:/Python')  # 第一种、绝对路径

# 二、将django项目的配置文件添加到os系统环绕搜寻的路径里
import os

os.environ['DJANGO_SETTINGS_MODULE'] = "OpenAI.settings"

# 三、加载django项目配置
import django

django.setup()

# 五、导入django项目的数据表类
from django.db.models import F, When, Case, Value
from user.models import UserProfile
from process.models import ChatHistory, ChatSession

userID = '07cc6c8250562fe5c463d7c018681c63'
chatID = '6cf840b38f0e4284f98947dd5b7c1884'
try:
    result = ChatHistory.objects.get(chatID__userID=userID, chatID=chatID, chatID__state=True)
    user = result.chatID.userID
    print(result)
except ChatHistory.DoesNotExist:
    print('不存在该记录')
# 六、导入tiktoken库统计token数量
import tiktoken


# def count_token(text):
#     SendToken = 0
#     ReceiveToken = 0
#     for messageItem in message:
#         if messageItem['role'] == 'user':
#             SendToken += len(encoding.encode(messageItem['content'])) + 7
#         else:
#             ReceiveToken += len(encoding.encode(messageItem['content']))
#     return SendToken, ReceiveToken


# encoding = tiktoken.encoding_for_model('gpt-3.5-turbo')
# ChatHistoryList = ChatHistory.objects.all()
# for ChatHistoryItem in ChatHistoryList:
#     try:
#         message = eval(ChatHistoryItem.message)
#     except:
#         continue
#     send_token, receive_token = count_token(message)
#     ChatHistoryItem.send_token = send_token
#     ChatHistoryItem.receive_token = receive_token
#     ChatHistoryItem.save()

# for ChatHistoryItem in ChatHistoryList:
#     message = ChatHistoryItem.message
#     if type(message) == str:
#         message = eval(message)
#     ChatHistoryItem.message = message
#     ChatHistoryItem.save()


